<?php

namespace App\Http\Controllers\Console;

use Validator;
use Illuminate\Http\Request;
use App\Model\Common\UserLog;
use App\Http\Controllers\Common\CommonController as Controller;

class CommonController extends Controller
{
    public function checkLogin()
    {
        $aid = session('user:uid');
        if ($aid) {
            return $aid;
        } else {
            return false;
        }
    }

    public function index(Request $request)
    {
        $map = [];
        $id = $request->input('id');
        if ($id) {
            $map['id'] = $id;
        }
        $name = trim($request->input('name'));
        if ($name) {
            $map['name'] = ['like', $name.'%'];
        }
        $title = trim($request->input('title/s'));
        if ($title) {
            $map['title'] = ['like', '%'.$title.'%'];
        }
        $m = !empty($this->modelName) ? model($this->modelName) : model($this->controller());

        $gets = $request->all() ?: [];
        foreach ($gets as $k => $v) {
            if ('' === $v || null === $v) {
                unset($gets[$k]);
            }
        }
        $sort = !empty($gets['sort']) ? $gets['sort'] : (!empty($this->defaultSort) ? $this->defaultSort : 'id');
        $order = (!empty($gets['order']) && 'asc' == $gets['order']) ? 'asc' : 'desc';
        unset($gets['sort'], $gets['order']);
        if (method_exists($m, 'mapDataFormat')) {
            $gets = $m->mapDataFormat($gets);
        }
        $map = array_merge($gets, $map);
        // dd($m->getTable());
        $fields = $m->getColumns();

        if (!in_array($sort, $fields)) {
            $sort = 'id';
        }
        foreach ($map as $key => $val) {
            if (!in_array($key, $fields)) {
                unset($map[$key]);
            }
        }
        if (!empty($gets['export']) && 'excel' == $gets['export']) {
            $opt = $m->getExportOpt();
            $list = $m->where($map)->field($opt['fields'])->order([$sort => $order])->select();
            if (method_exists($m, 'exportDataFormat')) {
                $list = $m->exportDataFormat($list);
            }
            $this->export($list, $opt);

            return;
        }
        $perpage = $request->input('per_page') ?: (empty($this->perpage) ? 20 : $this->perpage);
        $map['user_id'] = session('user:uid');
        $list = $m->where($map)->orderBy($sort, $order)->paginate($perpage);
        //print_r($list);
        if (method_exists($m, 'listDataFormat')) {
            $list = $m->listDataFormat($list);
        }
        // return $this->output(0, '', $list->toArray());
        if ($request->ajax() || (isset($_REQUEST['_async']) && 1 == $_REQUEST['_async'])) {
            return $this->output(0, '', $list->toArray());
        } else {
            $this->assign('list', $list);
            $this->assign('params', $map);
            // print_r($li)
            return $this->fetch();
        }
    }

    public function view(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            return $this->output(10005, '非法ID');
        }
        if (method_exists($this, 'others')) {
            $this->others();
        }
        $m = !empty($this->modelName) ? model($this->modelName) : model($this->controller());

        $mm = $m->find($id);
        if (method_exists($m, 'oneDataFormat')) {
            $mm = $m->oneDataFormat($mm, ['no_cache' => true, 'module' => 'console']);
        }

        $this->assign('data', $mm);

        return $this->fetch();
    }

    public function add(Request $request)
    {
        if ('GET' == $request->method()) {
            if (method_exists($this, 'others')) {
                $this->others();
            }

            return $this->fetch();
        } else {
            $data = $request->post();
            if (!empty($this->RULE['insert'])) {
                $validator = Validator::make($data, $this->RULE['insert']);

                if ($validator->fails()) {
                    return $this->output(10005, $validator->errors(), $data);
                }
            }
            $data = $this->requestDataFormat($data);
            $data['user_id'] = session('user:uid');
            $m = !empty($this->modelName) ? model($this->modelName) : model($this->controller());
            if (method_exists($m, 'add')) {
                $re = $m->add($data);
            } else {
                try {
                    $re = $m->fillData($data)->save();
                } catch (\Exception $e) {
                    $re = false;

                    return $this->output(10001, '新增失败:'.$e->errorInfo[2]);
                }
            }
            if ($re) {
                if (method_exists($m, 'refreshCache')) {
                    $m->refreshCache($m, 'insert');
                }
                UserLog::log($request, $m);

                return $this->output(0, '新增成功', $m->id);
            } else {
                return $this->output(10001, '新增失败'.$m->getError(), null);
            }
        }
    }

    public function edit(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            return $this->output(10005, '非法ID', null);
        }
        $m = !empty($this->modelName) ? model($this->modelName) : model($this->controller());

        if ('GET' == $request->method()) {
            $mm = $m->find($id);
            if (method_exists($m, 'oneDataFormat')) {
                $mm = $m->oneDataFormat($mm, ['module' => 'console']);
            }

            return $this->output(0, '', $mm);
        } else {
            $data = $request->post();
            if (!empty($this->RULE['update'])) {
                $validator = Validator::make($data, $this->RULE['update']);

                if ($validator->fails()) {
                    return $this->output(10005, $validator->errors(), $data);
                }
            }
            $data = $this->requestDataFormat($data);
            if (method_exists($m, 'edit')) {
                $re = $m->edit($data);
            } else {
                // $request->filter('editor_safe_filter');
                try {
                    $re = $m->where($m->getKeyName(), $id)->update($request->only($m->getColumns()));
                } catch (\Exception $e) {
                    $re = false;

                    return $this->output(10001, '新增失败:'.$e->errorInfo[2]);
                }
            }

            if (false !== $re) {
                if (method_exists($m, 'refreshCache')) {
                    $m->refreshCache($request, 'update');
                }
                UserLog::log($request, $m);

                return $this->output(0, '更新成功', null);
            } else {
                return $this->output(10001, '更新失败'.$m->getError(), $data);
            }
        }
    }

    public function del(Request $request)
    {
        $id = $request->post('id');
        if (!$id) {
            return $this->output(10005, '非法ID');
        }
        $m = !empty($this->modelName) ? model($this->modelName) : model($this->controller());

        if ($request->post('s')) {
            $d = $m->find($id);
            if (0 != $d['status']) {
                return $this->output(10005, '失效后的项目才可以清理');
            }
            $re = $m->where('id', $id)->delete();
        } else {
            $re = $m->where('id', $id)->update(['status' => 0]);
        }
        if ($re) {
            if (method_exists($m, 'refreshCache')) {
                $m->refreshCache($m, 'delete');
            }
            UserLog::log($request, $m);

            return $this->output(0, '删除成功', ['id' => $id]);
        } else {
            return $this->output(10005, '删除失败');
        }
    }

    public function requestDataFormat($data, $opt = [])
    {
        return $data;
    }

    private function export($list, $opt = [])
    {
    }
}
